<template>
  <div class="app-page">
    <aside-tree
      title="组织机构"
      :tree-data="treeData"
      :loading="$loadingPlugin.getTreeData"
      :mouse-button="false"
      @currentChange="currentChange"
      @refresh="getTreeData"
    />
    <div class="content">
      <el-table-form ref="form" class="formRight" :model="query" label-width="80px">
        <el-form-item class="merge-item">
          <el-select v-model="qType" style="width: 170px; margin-right: 2px;" placeholder="请选择">
            <el-option label="客户名称" value="csmName" />
            <el-option label="客户电话" value="csmPhone" />
            <el-option label="客户地址" value="csmAddress" />
            <el-option label="客户编号" value="csmCode" />
            <el-option label="关联安检单编号" value="checkId" />
          </el-select>
          <el-input v-model="csmText" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item :table-form-merge="2">
          <el-select v-model="timeType" style="width: 130px; margin-right: 2px;">
            <el-option label="安检日期" value="checkDt" />
            <el-option label="整改日期" value="lastDt" />
          </el-select>
          <el-date-picker
            v-model="date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :clearable="false"
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="userType" style="width: 130px; margin-right: 2px;">
            <el-option label="安检人" value="checkUser" />
            <el-option label="整改人" value="lastOperator" />
          </el-select>
          <el-input v-model="userName" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="状态:">
          <el-select v-model="query.repairStatus" clearable filterable placeholder="请选择">
            <el-option
              v-for="item in repairStatusMap"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户类型:">
          <el-select v-model="query.csmType" filterable clearable placeholder="请选择">
            <el-option
              v-for="item in customerTypeMap"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="隐患等级:">
          <el-select v-model="query.warnLevel" filterable clearable placeholder="请选择">
            <el-option
              v-for="item in warnLevelMap"
              :key="item.keyVal"
              :label="item.keyName"
              :value="item.keyVal"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="安检类型:">
          <el-checkbox-group v-model="checkList">
            <el-checkbox :label="1">定期安检</el-checkbox>
            <el-checkbox :label="2">随单安检</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <template v-slot:btns>
          <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
        </template>
      </el-table-form>
      <div style="margin-bottom: 20px;">
        <el-button type="primary" icon="el-icon-s-claim" @click="openTransferOrder">转派</el-button>
        <el-button type="primary" icon="el-icon-s-check" @click="openCheck">整改核查</el-button>
        <el-button type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
      </div>
      <!-- 表单 -->
      <lb-table
        ref="lbTable"
        v-loading="$loadingPlugin.fetchData"
        v-el-height-adaptive-table="{ bottomOffset: 10 }"
        border
        element-loading-text="加载中"
        :column="tableData.column"
        :data="tableData.data"
        pagination
        :total="tableData.total"
        :immediate-fetch="false"
        custom-column
        @fetch="fetchData"
        @selection-change="handleSelectionChange"
      />
    </div>
    <warnLevel ref="warnLevel" />
    <checkId ref="checkId" />
    <transfer ref="transfer" />
    <check ref="check" />
    <flow-info ref="flowInfo" />
    <security-check-detail ref="securityCheckDetail" :warn-level-map="warnLevelMap" />
    <risk-level-detail ref="riskLevelDetail" :warn-level-map="warnLevelMap" />
  </div>
</template>

<script>
  import { queryRiskTrackMap, queryGasWarningTraceList, queryRiskTrackListExport } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import AsideTree from '@/views/components/OrgTree'
  import WarnLevel from './components/WarnLevel'
  import CheckId from './components/CheckId'
  import { mapGetters } from 'vuex'
  import moment from 'dayjs'
  import { formatColumnMap, parseTime } from '@/utils'
  import Transfer from './components/Transfer'
  import Check from './components/Check'
  import FlowInfo from '../../components/FlowInfoCommon'
  import SecurityCheckDetail from '@/views/components/SecurityCheckDetail'
  import RiskLevelDetail from './components/CheckItem'

  export default {
    name: 'riskTrack',
    components: {
      AsideTree, CheckId, WarnLevel, Transfer, Check, FlowInfo, SecurityCheckDetail, RiskLevelDetail
    },
    data() {
      return {
        multipleSelection: [],
        treeData: [],
        currentOrg: null,
        checkList: [1, 2],
        customerTypeMap: [],
        repairStatusMap: [],
        warnLevelMap: [],
        qType: 'csmName',
        csmText: '',
        timeType: 'checkDt',
        date: [moment().startOf('month'), moment()],
        userType: 'checkUser',
        userName: '',
        query: {
          csmType: '',
          repairStatus: '',
          warnLevel: ''
        },
        tableData: {
          total: 0,
          column: [
            {
              type: 'index',
              fixed: true
            },
            {
              type: 'selection',
              fixed: true
            },
            {
              prop: 'csmCode',
              label: '客户编号'
            },
            {
              prop: 'csmName',
              label: '客户名称'
            },
            {
              prop: 'csmPhone',
              width: 110,
              label: '电话'
            },
            {
              prop: 'csmType',
              label: '客户类型',
              render: (h, { row }) => <span>{ row.csmType && formatColumnMap(this.customerTypeMap, 'value', row.csmType, 'desc') }</span>
            },
            {
              prop: 'csmAddress',
              width: 200,
              label: '地址'
            },
            {
              prop: 'orgName',
              width: 180,
              label: '责任机构'
            },
            {
              prop: 'checkType',
              label: '安检类型',
              render: (h, { row }) => {
                if (!row.checkType) return ''
                let checkTypeName = ''
                if (row.checkType === 1) {
                  checkTypeName = '随单安检'
                } else if (row.checkType === 2) {
                  checkTypeName = '定期安检'
                }
                return <span>{ checkTypeName }</span>
              }
            },
            {
              prop: 'checkId',
              width: 110,
              label: '关联安检单',
              render: (h, { row }) => <el-link onClick={() => this.openSecurityCheckDetail(row)}>{row.checkId}</el-link>
            },
            {
              prop: 'planName',
              label: '关联安检计划',
              width: 120,
              render: (h, { row }) => <el-link onClick={() => this.openOrderDetail(row)}>{row.planName}</el-link>
            },
            {
              prop: 'checkDt',
              width: 150,
              label: '安检时间',
              render: (h, { row }) => <span>{ row.checkDt && parseTime(row.checkDt, '{y}-{m}-{d} {h}:{i}') }</span>
            },
            {
              prop: 'checkUser',
              label: '安检人'
            },
            {
              prop: 'warnLevel',
              label: '隐患等级',
              render: (h, { row }) => <el-link underline={false} onClick={() => this.openRiskLevelDetail(row)}>{ row.warnLevel && formatColumnMap(this.warnLevelMap, 'keyVal', row.warnLevel, 'keyName') }</el-link>
            },
            {
              prop: 'repairStatus',
              label: '状态',
              render: (h, { row }) => <span>{ row.repairStatus && formatColumnMap(this.repairStatusMap, 'value', row.csmType, 'desc') }</span>
            },
            {
              prop: 'repairCount',
              align: 'right',
              label: '整改次数'
            },
            {
              prop: 'lastOperator',
              width: 100,
              label: '最后整改人'
            },
            {
              prop: 'lastDt',
              width: 150,
              label: '最后整改时间',
              render: (h, { row }) => <span>{ row.lastDt && parseTime(row.lastDt, '{y}-{m}-{d} {h}:{i}') }</span>
            },
            {
              prop: 'remark',
              width: 150,
              label: '备注'
            },
            {
              label: '操作',
              align: 'center',
              fixed: 'right',
              width: 80,
              render: (h, { row, $index }) => {
                return (
                  <div>
                    <el-link size='mini' underline={false} onClick={() => this.openFlow(row, $index)}>
                      流转信息
                    </el-link>
                  </div>
                )
              }
            }
          ],
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'exportDomain'
      ])
    },
    created() {
      this.getTreeData()
      this.queryOptionsMap()
    },
    methods: {
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        query[this.qtype] = this.csmText
        query[this.userType] = this.userName
        if (this.date && this.date.length === 2) {
          query[this.timeType] = moment(this.date[0]).format()
          query[`${this.timeType}End`] = moment(this.date[1]).format()
        }
        if (this.checkList.length === 0) query.checkType = 10000
        query.orgSNNo = this.currentOrg.orgSNNo
        const res = await queryGasWarningTraceList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      // 关联安检单
      async openSecurityCheckDetail(row) {
        await this.$refs.securityCheckDetail.open(row, 'info')
      },
      openOrderDetail() {},
      async openRiskLevelDetail(row) {
        await this.$refs.riskLevelDetail.open(row)
      },
      // 转派
      async openTransferOrder() {
        if (this.multipleSelection.length === 0) {
          this.$message.error('请选择要操作的行')
          return
        }
        await this.$refs.transfer.open(this.multipleSelection, this.currentOrg)
        this.$refs.lbTable.fetch()
      },
      async openCheck() {
        if (this.multipleSelection.length === 0) {
          this.$message.error('请选择要操作的行')
          return
        }
        await this.$refs.check.open(this.multipleSelection)
        this.$refs.lbTable.fetch()
      },
      async openFlow(row) {
        await this.$refs.flowInfo.open(row.traceCode, 32)
      },
      // 查询
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      // 导出
      exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'info'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.tableData.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          queryRiskTrackListExport({
            paramInfo: _this._getQuery(_this.query),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 获取组织机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.orgName,
          ...item
        }))
        this.treeData = getTreeData(data)
        this.currentOrg = this.treeData[0]
        this.$nextTick(() => {
          this.$refs.lbTable.fetch()
        })
      },
      // 选择组织机构变化
      currentChange(current) {
        this.currentOrg = current
      },
      // 查询枚举
      async queryOptionsMap() {
        const res = await queryRiskTrackMap()
        this.customerTypeMap = JSON.parse(res.data.csmType) // 客户类型
        this.repairStatusMap = JSON.parse(res.data.traceStatusMap) // 状态
        this.warnLevelMap = JSON.parse(res.data.warnLevel) // 隐患等级
      }
    }
  }
</script>

<style lang='scss' scoped>
.app-page {
  display: flex;
  // width: 100%;
  // height: calc(100vh - 130px);
  padding: 0;
  .content {
    flex: 1;
    width: 0;
    padding: 10px 10px 0 10px;
  }

  /deep/ .el-form-item__content {
    display: flex;
  }
}
</style>
